<template>
<div class="codeList"  v-if="!isShowChat">
    <div class="headbox">
        <div class="title"><h4>程序员</h4></div>
    <p class="warning">禁止发送色情、暴力、政治等敏感信息!违者封号!</p>
    </div>
    <ul class="assListBox">
    <li v-for="item in AssList" :key="item.code">
        <img :src="bg" alt="">
        <div>
        <h4>{{ item.title }}</h4>
        <span>{{  item.tag}}</span>
        <button @click="celectType(item)">使用</button>
        </div>
    </li>
</ul>
</div>
<div class="chatBox" v-if="isShowChat" style="width: 100%;">
    <div class="loding" v-if="isLoding"
      style="display: flex; justify-content: center; text-align: center; align-items: center; width: 100%;
      height: 100vh;
      ">
      <img src="@/assets/img/menu/loading.gif" alt="">
     </div>
<div class="chatData" v-show="!isLoding">
    <ul class="chatList" ref="chatContent">
   
          <li v-for="item in msgListArrHestry" :key="item.id">
            <img :src="item.role === 'system' ? ImgSys : logo" alt=""></img>
            <div>
              <div v-if="item.role !== 'system'" class="rightUser">
                {{ item.content }}
              </div>
              <!-- markdown -->
              <div v-else class="leftSys" v-html="markdown(item.content)"></div>
            </div>
          </li>
        </ul>
        <div class="send-chat-input">
          <!-- //这个可以正常输入 -->
          <textarea type="text" @keyup.enter="sendMessageAPI" v-model="messages.question" placeholder="请输入内容" />
          <!-- //这个element绑定的不会更新 每次只更新最后一次输入的值 -->
          <!-- <el-input v-model="messages" maxlength="3000" style="flex:1" type="textarea" placeholder="请输入内容" resize="none" /> -->
          <!-- {{ '有防抖会有延迟更新效果，' + messages }} -->
          <div class="sendBtn" :style="{ opacity: sendSteta ? 0.25 : 1, cursor: sendSteta ? 'not-allowed' : 'pointer' }"
            @click="sendMessageAPI">
            <img style="pointer-events: none;" src="@/assets/img/chat/sendmsg.png" alt="">
          </div>

          <!-- <el-button @click="sendMessage">sendMessage</el-button> -->
        </div>


</div>
</div>



</template>
<script lang='ts' setup>

import {assistantList , type IAssistantItem } from '@/api/chat'
import { onBeforeMount ,ref,reactive,watch} from 'vue';
import { getChatMassageList, addChat, sendMessageSSE  } from '@/api/chat'
import {ElNotification} from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import md from '@/utils/markdown'
import ImgSys from '@/assets/img/logo1x.png'
import { userInfoStore } from "@/stores/userInfo";

const {userId,logo,} = userInfoStore().userInfo
const {token} = userInfoStore()
const route = useRoute()
const router = useRouter()
const AssList = ref<IAssistantItem[]>([])
const bg ='http://ai.xuexiluxian.cn/assets/optimization-BU-OI7rU.png'
// 历史聊天
const msgListArrHestry = ref([])

//获取功能列表
const getAssCodeList =()=>{
    assistantList().then(
        (res)=>{
            // console.log('程序员列表',res);
            AssList.value = res.data
        },
        (rej)=>{},
    )

}



//会话窗口 发送信息
const messages = reactive({
  id: '1',
  question: '',
  userId
})
// 控制发送按钮状态
const sendSteta = ref<boolean>(false)

//sse接口链接
const sendMessageAPI = async () => {
  messages.id = route.query.chatId;
  console.log('发送');

  let res = await fetch(import.meta.env.VITE_APP_URL+'/xlx-chat/chatMessage/sendMessageSSE', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token,
    },
    body: JSON.stringify({
      ...messages,
    }),
  });
  console.log('流数据', res);
  if (res.status !== 200) {
    ElNotification({ type: 'warning', message: '发送失败' });
    sendSteta.value = false;
    return;
  }
  const contentType = res.headers.get('Content-Type');
  if (contentType === 'application/json') {
    const jsonResponse = await res.json();
    ElNotification({
      type: 'warning',
      message: jsonResponse.errorMessage,
    });
    sendSteta.value = false; // 按钮状态
  } else {
    ElNotification({
      type: 'success',
      message: '发送成功',
    });
    msgListArrHestry.value.push({
      role: 'user',
      content: messages.question,
    });
    messages.question = '';
// res是请求回来的结果

    let reader = res.body?.getReader();
    let decoder = new TextDecoder('utf-8');
    let accumulatedData = ''; // 累积接收到的数据
    let len = msgListArrHestry.value.length;
    msgListArrHestry.value.push({
      role: 'system',
      content: '',
    });

    let index = len; // 记录最新系统消息的位置

    while (true) {
      const { done, value } = await reader?.read();
      if (done) {
        sendSteta.value = false; // 可以再次发送
        break;
      }

      const chunk = decoder.decode(value, { stream: true });
      accumulatedData += chunk;  // 累积接收的数据块

      const lines = chunk.split('\n');
      accumulatedData = '';  // 清空累积数据

      let str = ''
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        if (line.startsWith('data:')) {
          let dataStr = line.substring(5).trim();
          // console.log('dataStr', JSON.stringify(dataStr));
          str += dataStr
        }
      }

      // 捕捉 Token 消耗信息

    


      try{
        // 如果str是有效的JSON字符串，解析它
        if (str) {
          const parsedData = JSON.parse(str);  // 解析事件数据
          console.log('解析后的数据', parsedData);
          // 你需要检查parsedData里有没有content字段，再更新视图
          if (parsedData.content) {
            msgListArrHestry.value[index].content += parsedData.content;  // 追加内容到视图中
            scrollToBottom() //下拉滚动
          }
        }
      } catch (e) {
        console.log('JSON解析错误:', e);
      }
    }
  }
};

// 滚动条向下
// 滚动到底
const chatContent = ref(null)
// 向下滚动
const scrollToBottom = ()=>{
  nextTick(()=>{
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value.scrollHeight
    }
  }) //dom更新完成执行
}


//拿历史数据
const isLoding = ref(false)
const getHistoryData = async (id:number|string) => {
  // sendSteta.value = true; // 禁用发送按钮
  isLoding.value = true
  try {
    let res = await getChatMassageList({
      chatId: id as string
    })
    
    if (res.code === 0){
      console.log(res);
      msgListArrHestry.value = res.data
    //   isdefinedChat.value = true
      scrollToBottom() //向下滚动一次 这个功能没有实现
    }else{

    }
  } catch (error) {
    console.log(error);
  } finally{
    isLoding.value = false
  }
}



const celectType = (item:any)=>{
  console.log('item', item);

    // if(chatType == null){
    //   ElNotification({
    //     title: '提示',
    //     message: '请选择一个类型',
    //     type: 'warning',
    //   })
      // return
    //  }


  addChat({ userId, type: item.code, assistantId: item.assistantId }).then(
    (res) => {
      console.log(res);

      if(res.code === 500){
        ElNotification({
          message: res.errorMessage,
          type: 'warning',
        })
      }else{
        ElNotification({
          message: res.errorMessage,
          type: 'success',
        })
        router.push({
          path: "/programmers/" + item.code,
          query: { chatId: res.data.chatId }
        })
        getHistoryData(res.data.chatId)
      }
    },
    (err) => { 
      console.log(err);
    },
  )
}

const isShowChat = ref(false)
watch(() => route.params.chattype, (newValue) => {
  // console.log('newValue', newValue);
  if (newValue) {
    // getHistoryData(newValue as string)  //信息列表
    isShowChat.value = true
  }else{
    isShowChat.value = false
  }
})
//历史数据
watch(() => route.query.chatId, (newValue) => {
  // console.log('newValue', newValue);
  if (newValue) {
    getHistoryData(newValue as string)  //信息列表
    isShowChat.value = true
  } else {
    isShowChat.value = false
  }
})

onBeforeMount(()=>{
    if (route.query.chatId){
      getHistoryData(route.query.chatId)
  }
  getAssCodeList()
})
// md
const markdown = (text:string)=>{
  return md.render(text)
}


</script>
<style scoped lang='scss'>

.headbox{
.title{
    border-left:  5px solid #C90000;
    padding-left: 10px;
    display: flex;
    align-items: center;
  height: 37px;
    h4 {
        width: 112px;
        line-height: 37px;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 23px;
        color: #232323;
        text-align: center;
        font-style: normal;
        text-transform: none;
      }
  }

  p{
background: #FFF7F7;
  border-radius: 8px 8px 8px 8px;
  // border: 1px solid #C90000;
  border:.15vw solid #C90000;
  color: #C90000;
height: 42px;
width: 100%;
line-height: 42px;
padding-left: 15px;
margin-top: 30px;
box-sizing: border-box;
}
}
.assListBox{
    display: flex;
    flex-wrap: wrap;
    padding: 15px;
    height: calc(100vh - 130px - 36px);
    justify-content: flex-start; /* 子元素紧密排列在左侧 */ 
    background-color:#ffffff;
    overflow-y: auto;
    overflow-x:hidden;

    
    -webkit-appearance: none; /* 移除 WebKit 的默认样式 */
    appearance: none; /* 移除所有现代浏览器的默认样式 */
::-webkit-scrollbar {
    width: 12px; /* 滚动条宽度 */
}
::-webkit-scrollbar-track {
    background-color: #f5f5f5; /* 轨道背景颜色 */
}
::-webkit-scrollbar-thumb {
    background-color: red; /* 滚动块颜色 */
    border-radius: 50%; /* 滚动块圆角 */
}
::-webkit-scrollbar-thumb:hover {
    background-color: #555; /* 滚动块悬停时的颜色 */
}
    li{
        flex: 1 30%;
        min-width: 347px;
        margin: 5px 5px 0 0;
        img{
            width: 100%;
            filter: drop-shadow( 2px 2px 2px rgb(201,0,0));
        }
        position: relative;
        div{
            position: absolute;
            top: 0;
            z-index: 1;
            display: flex;
            flex-direction: column;
            
            width: 100%;
            height: 100%;
            padding: 26px;
            box-sizing: border-box;
            h4{
                font-size: 26px;
                line-height: 52px;
                color: #232323;
            }
            span{
                margin: 15px 0  150px 0;
                color: #acacac;
            }
            button{
    width: 240px;
    height: 34px;
    cursor: pointer;
    font-size: 18px;
    color: #fff;
    background: #c90000;
    border-radius: 8px;
    position: absolute;
    left: 50%;
    border: 1px solid gray;
    bottom: 34px;
    margin-left: -120px;
            }
        }
    }
}



// .chatBox{
//   position: relative;
//   box-sizing: border-box;
//   .loding{
//     position: absolute;
//     height: 100%;
//     width: 100%;
//   }
.chatData{
    display: flex;
      flex-direction: column;
      height: calc(100vh - 36px);
      box-sizing: border-box;
      width: 100%;
.chatList{
  width: 100%;
  flex: 1;
  overflow-y: auto;
  box-sizing: border-box;
  li {
    display: flex;
    width: 100%;
    box-sizing: border-box;
    margin-top: 15px;
    padding: 0 5px;
    img{
      width: 40px;
      height: 40px;
      margin: 0 10px;
      border-radius: 50%;
    };
    div{
      padding: 13px 24px 26px 13px;
      border-radius: 5px;
      font-weight: 500;
    }
  }
}


.send-chat-input:focus-within {
  border-color: red;
  /* 当子元素获得焦点时，改变父元素的边框颜色 */
}

.send-chat-input {
  width: 100%;
  // height: 60px;
  display: flex;
  border: 1px transparent solid;
  transition: border .3s;
  box-sizing: border-box;
  align-items: center;
  background: #FFFFFF;

  textarea {
    height: 60px;
    font-size: 18px;
    flex: 1;
    box-sizing: border-box;
    padding: 10px 18px;
    outline: none;

  }

  .sendBtn {
    cursor: pointer;
    width: 50px;
    height: 50px;
    box-sizing: border-box;
    // background-color: #c90000;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-self: center;
    transition: background-color 1s;
    position: relative;
    &:hover {
 
      background-color: rgba($color: #c90000, $alpha: .4);
    }

    img {
        width: 20px;
        height: 20px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%)

    }
  }
}
}
.leftSys{
  background: #FFFFFF;
}
.rightUser{
  background-color:rgb(245, 226, 221) ;
  font-size: 16px;
}
// }





</style>
